package servlet;

import dao.materialDAO;
import entity.Page;
import entity.materialBean;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import utils.StrFilter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 王开心
 * @Date: 2024/04/17/21:53
 * @Description:
 */
@WebServlet("/group/material/material_list")
public class MaterialServlet extends HttpServlet{

    public MaterialServlet() {
        super();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("Loading data...");
        HttpSession session = req.getSession(); // 获取会话
        // 获取先前的查询条件
        String previousName = (String) session.getAttribute("previousName");
        String previousId = (String) session.getAttribute("previousId");
        String previousType = (String) session.getAttribute("previousType");


        String name=StrFilter.filter(req.getParameter("name"));
        String id=StrFilter.filter(req.getParameter("id"));
        String type= StrFilter.filter(req.getParameter("type"));

        Page materialPage = (Page) session.getAttribute("materialPage");
        // 检查查询条件是否已更新
        if (!name.equals(previousName) || !id.equals(previousId) || !type.equals(previousType)) {
            // 重新初始化页数
            materialPage=null;
        }

        if (materialPage == null  ) {
            materialPage = new Page();
            session.setAttribute("materialPage", materialPage);
        }

        //分页逻辑
        if(req.getParameter("currentPage") != null) {
            materialPage.setCurrentPage(Integer.parseInt(req.getParameter("currentPage"))) ;
        }


        materialDAO dao =new materialDAO();
        List<materialBean> materialBeanList =dao.findMaterial(name,id,type,materialPage);

        // 保存当前查询条件以供下次检查
        session.setAttribute("previousName", name);
        session.setAttribute("previousId", id);
        session.setAttribute("previousType", type);


        req.setAttribute("materialPage",materialPage);
        req.setAttribute("list", materialBeanList);
        req.setAttribute("name",name);
        req.setAttribute("id",id);
        req.setAttribute("type",type);
        req.getRequestDispatcher("material_list.jsp").forward(req, resp);
    }
}


